package web

import (
	"fmt"
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
	"strings"
)

// Dictionary 字典表管理
type Dictionary struct {
	DictionaryBll *bll.Dictionary `inject:""`
}

// QueryPage 查询分页数据
func (a *Dictionary) QueryPage(ctx *context.Context) error {
	pageIndex, pageSize := ctx.GetPageIndex(), ctx.GetPageSize()

	params := schema.DictionaryQueryParam{
		Name:     ctx.Query("name"),
		ParentID: ctx.Query("parent_id"),
	}

	total, items, err := a.DictionaryBll.QueryPage(params, pageIndex, pageSize)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	result := map[string]interface{}{
		"list": items,
		"pagination": map[string]interface{}{
			"total":    total,
			"current":  pageIndex,
			"pageSize": pageSize,
		},
	}

	return ctx.ResSuccess(result)
}

// QueryTree 查询树形数据
func (a *Dictionary) QueryTree(ctx *context.Context) error {
	var (
		root  string
		level int
		items []map[string]interface{}
		err   error
	)
	root = ctx.Query("root")
	level = ctx.QueryInt("level")

	items, err = a.DictionaryBll.QueryTree(root, level)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(items)
}

// QueryShowTree 查询树形数据展示
func (a *Dictionary) QueryShowTree(ctx *context.Context) error {
	var (
		root  string
		level int
		items []map[string]interface{}
		err   error
	)
	root = ctx.Query("root")
	level = ctx.QueryInt("level")

	items, err = a.DictionaryBll.QueryTree(root, level, true)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(items)
}

// QueryNameList 查询字典名列表
func (a *Dictionary) QueryNameList(ctx *context.Context) error {
	var (
		list  []string
		root  string
		items []map[string]interface{}
		err   error
	)
	root = ctx.Query("root")
	list = ctx.QueryList("code")
	items, err = a.DictionaryBll.QueryTree(root, 1, true)
	if err != nil {
		return ctx.ResErrBadRequest(err)
	}
	if len(list) > 0 {
		for i, v := range list {
			list[i] = ""
			for _, m := range items {
				if m["code"] == v {
					list[i] = m["name"].(string)
					break
				}
			}
		}
	} else {
		for _, m := range items {
			list = append(list, m["name"].(string))
		}
	}
	return ctx.ResSuccess(list)
}

// GetByCode 根据Code获取名字
func (a *Dictionary) GetByCode(ctx *context.Context) error {
	var (
		item *schema.Dictionary
		err  error
		name string
	)
	item, err = a.DictionaryBll.GetByCode(ctx.Query("code"))
	if err != nil {
		return ctx.ResErrBadRequest(err)
	}
	name = item.Name
	return ctx.ResSuccess(name)
}

// Get 精确查询数据
func (a *Dictionary) Get(ctx *context.Context) error {
	item, err := a.DictionaryBll.Get(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(item)
}

// Create 创建数据
func (a *Dictionary) Create(ctx *context.Context) error {
	ctx.WriteOperateLog("Dictionary.Create", "字典表管理-创建数据")
	var item schema.Dictionary
	if err := ctx.ParseJSON(&item); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	item.Creator = ctx.GetUserID()
	err := a.DictionaryBll.Create(&item)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// Update 更新数据
func (a *Dictionary) Update(ctx *context.Context) error {
	ctx.WriteOperateLog("Dictionary.Update", "字典表管理-更新数据")
	var item schema.Dictionary
	if err := ctx.ParseJSON(&item); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	err := a.DictionaryBll.Update(ctx.Param("id"), &item)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// DeleteMany 删除多条数据
func (a *Dictionary) DeleteMany(ctx *context.Context) error {
	ctx.WriteOperateLog("Dictionary.DeleteMany", "字典表管理-删除多条数据")
	ids := strings.Split(ctx.Query("batch"), ",")

	for _, id := range ids {
		err := a.DictionaryBll.Delete(id)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		}
	}

	return ctx.ResOK()
}

// Delete 删除数据
func (a *Dictionary) Delete(ctx *context.Context) error {
	ctx.WriteOperateLog("Dictionary.Delete", "字典表管理-删除数据")
	err := a.DictionaryBll.Delete(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// MoveUp 数据排序上移
func (a *Dictionary) MoveUp(ctx *context.Context) error {
	id := ctx.Param("id")
	item, err := a.DictionaryBll.Get(id)
	if err != nil {
		return ctx.ResErrInternalServer(err, 500)
	} else if item == nil {
		return ctx.ResErrBadRequest(fmt.Errorf("找不到数据"), 400)
	}
	if item.Sequence <= 1 {
		return ctx.ResErrBadRequest(fmt.Errorf("无法上移"), 401)
	}
	err = a.DictionaryBll.ChangeSequence(item.ParentID, item.Sequence, item.Sequence-1)
	if err != nil {
		return ctx.ResErrInternalServer(err, 500)
	}
	return ctx.ResOK()
}

// MoveDown 下移
func (a *Dictionary) MoveDown(ctx *context.Context) error {
	id := ctx.Param("id")
	item, err := a.DictionaryBll.Get(id)
	if err != nil {
		return ctx.ResErrInternalServer(err, 500)
	} else if item == nil {
		return ctx.ResErrBadRequest(fmt.Errorf("找不到数据"), 400)
	}
	if item.Sequence == a.DictionaryBll.GetLastSequence(item.ParentID) {
		return ctx.ResErrBadRequest(fmt.Errorf("无法下移"), 401)
	}
	err = a.DictionaryBll.ChangeSequence(item.ParentID, item.Sequence, item.Sequence+1)
	if err != nil {
		return ctx.ResErrInternalServer(err, 500)
	}
	return ctx.ResOK()
}
